import PropTypes from 'react-router/lib/PropTypes';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {Button, Form, Modal,message, Spin} from 'antd'
const createForm = Form.create;
const FormItem = Form.Item;
import isEmpty from 'lodash/isEmpty'
import Immutable from 'immutable'
const is = Immutable.is;
import * as OnlineAction from '../actions/online'
import { WeaErrorPage, WeaTools, WeaSearchBrowserBox } from 'ecCom'
import {getParamsByConditions} from '../utils'
import {
  WeaTab,
  WeaTop,
  WeaSearchGroup,
  WeaRightMenu,
  WeaPopoverHrm,
  WeaLeftRightLayout,
  WeaOrgTree,
  WeaSelect,
} from 'ecCom'
import {WeaTable} from 'comsRedux'
const WeaTableAction = WeaTable.action;
import * as PublicFunc from '../utils/pulic-func';

let _this;
class Online extends React.Component {
  static contextTypes = {
    router: PropTypes.routerShape
  }
  constructor(props) {
    super(props);
    _this = this;
    const funcs = ['onOperatesClick','jumpToHrmCard'];
    funcs.forEach(f=> this[f] = this[f].bind(this))
  }
  componentDidMount() {
    const {condition, actions} = this.props;
    actions.getHrmSearchCondition();
    actions.doSearch();
  }
  componentWillReceiveProps(nextProps) {
    const { actions } = this.props;
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    if(keyOld !== keyNew) {
      actions.saveFormFields();
      actions.setShowSearchAd(false);
      this.componentDidMount();
    }
  }
  shouldComponentUpdate(nextProps, nextState) {
    return  !is(this.props.title,nextProps.title) ||
            !is(this.props.condition, nextProps.condition)||
            !is(this.props.fields, nextProps.fields)||
            !is(this.props.dataKey, nextProps.dataKey)||
            this.props.showSearchAd !== nextProps.showSearchAd ||
            !is(this.props.searchParamsAd, nextProps.searchParamsAd)||
            !is(this.props.comsWeaTable,nextProps.comsWeaTable);
  }
  componentWillUnmount() {
    const {actions} = this.props;
    actions.saveFormFields();
    actions.setShowSearchAd(false);
  }
  render() {
    // console.log('render----------------------------');
    const {actions,dataKey, title,fields,searchParamsAd,showSearchAd,comsWeaTable} = this.props;
    const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
    const tableNow = comsWeaTable.get(tablekey);
    const loadingTable = tableNow.get('loading');
    return (
      <div className='wea-myhrm-Online'>
      <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
        <WeaTop
          title={title}
          loading={loadingTable}
          icon={<i className='icon-coms-hrm' />}
          iconBgcolor='#217346'
          buttons={[]}
          buttonSpace={10}
          showDropIcon={false}
          dropMenuDatas={this.getRightMenu()}
          onDropMenuClick={this.onRightMenuClick.bind(this)}
        >
          <div style={{height: '100%'}}>
              <WeaLeftRightLayout leftCom={this.getTree()} leftWidth={25} >
                  <WeaTab
                      onlyShowRight={true}
                      buttonsAd={this.getTabButtonsAd()}
                      searchType={['base','advanced']}
                      searchsBaseValue={searchParamsAd.get('lastname')}
                      setShowSearchAd={bool => {actions.setShowSearchAd(bool)}}
                      hideSearchAd={() => actions.setShowSearchAd(false)}
                      searchsAd={<Form horizontal>{this.getSearchs(true)}</Form>}
                      showSearchAd={showSearchAd}
                      onSearch={v => {actions.doSearch()}}
                      onSearchChange={v => {
                        actions.saveFormFields({
                            ...fields.toJS(),
                            lastname:{name:'lastname',value:v},
                          });
                        }}
                  />
                    <Spin spinning={loadingTable}>
                      <WeaTable sessionkey={dataKey}
                        hasOrder={true}
                        needScroll={true}
                        getColumns={c=>this.reRenderColumns(c)}
                        onOperatesClick={this.onOperatesClick}
                        />
                    </Spin>
            </WeaLeftRightLayout>
          </div>)
        </WeaTop>
        </WeaRightMenu>
      </div>
    )
  }
  reRenderColumns(columns){
    columns.forEach(c=>{
        if(c.dataIndex=='lastname'){
            c.render = function(text, record){
                return  <span style={{cursor:'pointer'}} className='wea-hrm-linkstyle' onClick={_this.jumpToHrmCard.bind(null,record.id)}>{record.lastname}</span>
            }
        } else {
          c.render = function(text, record){
              let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
              return <span dangerouslySetInnerHTML={{__html: valueSpan}}></span>
            }
        }
    })
    return columns;
  }
  jumpToHrmCard(hrmId,...rest){
    // this.context.router.push({pathname:'/main/hrm/resource/HrmResourceBase',state:hrmId})
    // this.context.router.push({pathname:'/main/hrm/resource4Formal/HrmResourceBase4Formal',state:hrmId})
    window.open('/spa/hrm/index.html#/main/hrm/resource4Formal/HrmResourceBase4Formal/' + hrmId)
  }
  onOperatesClick=(record,index,operate,flag,argumentString)=>{
      const fn = operate.href ? operate.href.split(':')[1].split('(')[0] : '';
      const id = record.id ? record.id : '';
      PublicFunc[fn](id);
  }
  getTabButtonsAd() {
      const {actions,searchParamsAd} = this.props;
      return [
          (<Button type="primary" onClick={()=>{actions.doSearch();actions.setShowSearchAd(false)}}>搜索</Button>),
          (<Button type="ghost" onClick={()=>{actions.saveFormFields()}}>重置</Button>),
          (<Button type="ghost" onClick={()=>{actions.setShowSearchAd(false)}}>取消</Button>)
      ]
  }
  getSearchs(bool) {
    const {condition} = this.props;
    let searchGroupArr = [];
    condition && condition.toJS().forEach((item,index)=>{
      searchGroupArr.push(
        <WeaSearchGroup
           needTigger={true}
           title={this.getTitle(index)}
           showGroup={this.isShowFields(index)}
           items={this.getFields(bool,index)}
         />
      )
    })
    return searchGroupArr;
  }
  getTitle(index=0) {
      const {condition} = this.props;
      return !isEmpty(condition.toJS()) && condition.toJS()[index].title
  }
  isShowFields(index=0) {
      const {condition} = this.props;
      return !isEmpty(condition.toJS()) && condition.toJS()[index].defaultshow
  }
  getFields = (bool=false,index=0) => {
      const {condition,actions} = this.props;
      const browserConditions = condition.toJS();
      const fieldsData = !isEmpty(browserConditions) && browserConditions[index].items;
      let items = new Array();
      fieldsData.forEach( field => {
        field && items.push({
            com:(<FormItem
                label={`${field.label}`}
                labelCol={{span: `${field.labelcol}`}}
                wrapperCol={{span: `${field.fieldcol}`}}>
                    {WeaTools.getComponent(field.conditionType, field.browserConditionParam, field.domkey,this.props, field)}
                </FormItem>),
            colSpan:field.colSpan || 2
        });
      });
     return items;
  }
  getTree() {
    const {actions,loading} = this.props;
    return (
      <WeaOrgTree
        loading
        needDropMenu={false}
        needSearch
        isLoadSubDepartment={true}
        topPrefix={'hrmOnline'}
        treeNodeClick={this.treeNodeClick}
      />
    )
  }
  treeNodeClick = (nodeObj) => {
    const type = nodeObj.node.props.type || '0';
    const id = nodeObj.node.props.id || '';
    const name = nodeObj.node.props.name || '';
    const {actions,fields}=this.props;
    let paras = {};
    actions.setShowSearchAd(false);
    if(type=='1'){
      paras['subcompanyid1']={name:'subcompanyid1',value:id,valueSpan:name}
    }
    if(type=='2'){
      paras['departmentid']={name:'departmentid',value:id,valueSpan:name}
    }
    actions.saveFormFields(paras);
    actions.doSearch();
  }
  getRightMenu(){
      const keys = this.getSelectedRowKeys();
      const arr = [{
          icon: <i className='icon-coms-ws'/>,
          content:'搜索'
        }, {
          icon: <i className='icon-coms-task-list'/>,
          content:'显示定制列'
        }
        // ,{
        //     icon: <i className='icon-Right-menu-Batch-sharing'/>,
        //     content:'收藏',
        // },{
        //     icon: <i className='icon-Right-menu-Custom'/>,
        //     content:'帮助'
        // }
      ];
      return arr;
  }
  onRightMenuClick(key){
    const {actions,comsWeaTable} = this.props;
    switch(key){
        case '0':
            this.doSearch();
            break;
        case '1':
            this.definedColumn();
            break;
    }
  }
  getSelectedRowKeys(){
    const {comsWeaTable,dataKey} = this.props;
    const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
    const tableNow = comsWeaTable.get(tablekey);
    return tableNow.get('selectedRowKeys').toJS();
  }
  sendEmessage(){
      const keys = this.getSelectedRowKeys();
      const ids = keys ? keys.join(',') : '';
      PublicFunc.sendEmessage(ids);
  }
  exportExcel(){
      const {actions, dataKey} = this.props;
      dataKey && actions.exportExcel(dataKey);
  }
  doSearch() {
      const {actions} = this.props;
      actions.doSearch();
  }
  definedColumn() {
      const {actions, dataKey} = this.props;
      actions.setColSetVisible(dataKey, true);
      actions.tableColSet(dataKey, true);
  }
}
//组件检错机制
class MyErrorHandler extends React.Component {
  render() {
    const hasErrorMsg = this.props.error && this.props.error !== "";
    return(
      <WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
    );
  }
}

Online = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(Online);

//form 表单与 redux 双向绑定
Online = createForm({
  onFieldsChange(props, fields) {
        props.actions.saveFormFields({...props.fields.toJS(), ...fields});
    },
  mapPropsToFields(props) {
    return props.fields.toJS();
    }
})(Online);


// 把 state map 到组件的 props 上
const mapStateToProps = state => {
    // console.log('==================================================state',state);
  const {hrmOnline,comsWeaTable} = state;
  return {
    title:hrmOnline.get('title'),
    condition:hrmOnline.get('condition'),
    fields: hrmOnline.get('fields'),
    dataKey:hrmOnline.get('dataKey'),
    showSearchAd:hrmOnline.get('showSearchAd'),
    searchParamsAd: hrmOnline.get('searchParamsAd'),
    comsWeaTable: comsWeaTable, //绑定整个table
  }
}

// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
  return {
    actions: bindActionCreators({...OnlineAction,...WeaTableAction}, dispatch)
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Online);